package com.onlineclass.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mvc.annotation.Controller;
import com.mvc.annotation.RequestMapping;
import com.mvc.core.ModelAndView;
import com.onlineclass.dao.CourseDAO;
import com.onlineclass.dao.TagDAO;


@Controller
@RequestMapping("/course")
public class CourseController {

	private TagDAO tagDAO = new TagDAO();
	private CourseDAO courseDAO = new CourseDAO();
	
	/**
	 * 根据分类Id查询课程
	 * @param tag
	 * @return
	 */
	@RequestMapping("/list.do")
	public ModelAndView list(Integer direction, Integer tag, Integer isPay, Integer order) {
		ModelAndView model = new ModelAndView("/course_list.jsp");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tags1", tagDAO.list(0));
		
		List<Integer> ids = new ArrayList<Integer>();//保存所有的二级分类id
	
		//如果前端点击了某个二级类别
		if(tag!=null) {
			ids.add(tag);
		} 
		if(direction!=null) {
			if(tag==null) ids = tagDAO.listTags(direction);
			map.put("tags2", tagDAO.list(direction));
		}
		
		map.put("courses", courseDAO.list(ids, isPay, order));	
		model.setMap(map);	
		return model;
	}
	
	@RequestMapping("/search.do")
	public ModelAndView search(String kw) {
		ModelAndView model = new ModelAndView("/course_list.jsp");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tags1", tagDAO.list(0));
		map.put("courses", courseDAO.search(kw.trim()));	
		model.setMap(map);	
		return model;
	}


	/**
	 * 根据课程id查询详情
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail.do")
	public ModelAndView findById(Integer id) {
		courseDAO.updateHits(id);
		ModelAndView model = new ModelAndView("/course_detail.jsp");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("course", courseDAO.findById(id));
		map.put("relatedCourses", courseDAO.relatedCourse(id));
		model.setMap(map);
		return model;
	}
	
}